import * as types from '../mutation-types'
import http from '@/utils/http'
export default {
  state: {
    // 购物车数据
    list: [],
    // 数据是否已加载
    loaded: false,
    // 购物时，已选择的地址
    checked: null,
    // 添加地址返回的地址
    referPage: null
  },
  getters: {
    checkedAddress: state => {
      if (state.list.length === 0) {
        return null
      }
      // 手动选择的地址
      if (state.checked) {
        return state.checked
      }
      let address = null
      // 默认地址
      state.list.some((item) => {
        if (item.is_default) {
          address = item
          return true
        }
      })
      if (address) {
        return address
      }
      // 返回第一条
      return state.list[0]
    }
  },
  mutations: {
    [types.SET_ADDRESS_LIST]: (state, list) => {
      state.list = list
    },
    [types.SET_ADDRESS_LOAD_STATUS]: (state, status) => {
      state.loaded = status
    },
    [types.DELETE_ADDRESS]: (state, index) => {
      state.list.splice(index, 1)
    },
    [types.SET_REFER_PAGE]: (state, referPage) => {
      state.referPage = referPage
    },
    [types.SET_CHECKED_ADDRESS]: (state, address) => {
      state.checked = address
    }
  },
  actions: {
    getAddresses: ({commit}) => {
      return new Promise((resolve, reject) => {
        http.get('/addresses').then((response) => {
          commit(types.SET_ADDRESS_LIST, response.data)
          commit(types.SET_ADDRESS_LOAD_STATUS, true)
          resolve(response)
        }).catch((error) => {
          reject(error)
        })
      })
    },
    addAddress: ({dispatch, state}, address) => {
      return new Promise((resolve, reject) => {
        http.post('/addresses', address).then((response) => {
          dispatch('getAddresses')
          resolve(response)
        }).catch((error) => {
          reject(error)
        })
      })
    },
    deleteAddress: ({commit, state}, index) => {
      return new Promise((resolve, reject) => {
        http.delete('/addresses/' + state.list[index].id).then((response) => {
          commit(types.DELETE_ADDRESS, index)
          resolve(response)
        }).catch((error) => {
          reject(error)
        })
      })
    },
    updateAddress: ({dispatch}, data) => {
      return new Promise((resolve, reject) => {
        http.put('/addresses/' + data.id, data).then((response) => {
          dispatch('getAddresses')
          resolve(response)
        }).catch((error) => {
          reject(error)
        })
      })
    },
    setDefaultAddress: ({dispatch}, address) => {
      return new Promise((resolve, reject) => {
        http.put('/addresses/' + address.id + '/default').then((response) => {
          dispatch('getAddresses')
          resolve(response)
        }).catch((error) => {
          reject(error)
        })
      })
    }
  }
}
